import * as colorMap from 'colormap';
import * as colorScale from 'colormap/colorScale';

/**
 * 绘制colorBar
 * @param colormap 颜色表
 * @param n 画多少个
 * @param canvas 画布
 * @param orientation 横着还是竖着
 */
function drawColorMap(
  colormap: string[],
  n: number,
  canvas: HTMLCanvasElement,
  //vertically and horizontally
  orientation: 'vertically' | 'horizontally' = 'horizontally',
) {
  const width = canvas.width,
    height = canvas.height;
  const ctx = canvas.getContext('2d');
  if (orientation === 'horizontally') {
    const barHeight = height / 2;
    const linearGradient = ctx.createLinearGradient(0, 0, width, 0);
    for (let j = 0; j < n; j++) {
      linearGradient.addColorStop(j / n, colormap[j]);
    }
    ctx.fillStyle = linearGradient;
    ctx.fillRect(0, 0, width, barHeight);
  } else {
    const barWidth = width / 2;
    const linearGradient = ctx.createLinearGradient(0, 0, 0, height);
    for (let j = 0; j < n; j++) {
      linearGradient.addColorStop(j / n, colormap[j]);
    }
    ctx.fillStyle = linearGradient;
    ctx.fillRect(0, 0, barWidth, height);
  }
}

// 重载函数，根据format的值，返回不同的类型
function getColorMap(
  name: string,
  nshades: number,
  format?: 'hex',
  alpha?: number,
): string[];
function getColorMap(
  name: string,
  nshades: number,
  format?: 'float',
  alpha?: number,
): number[][];
function getColorMap(
  name: string,
  nshades: number,
  format: 'hex' | 'float' = 'hex',
  alpha?: number,
) {
  const cmap = colorScale[name];
  if (!cmap) {
    return [];
  }
  if (cmap.length > nshades) {
    nshades = cmap.length;
  }
  return colorMap({ colormap: name, nshades, format, alpha });
}

function makeColorMap(name: string) {
  const jetColorMap = getColorMap(name, 72, 'float', 1);
  return jetColorMap;
}

export { drawColorMap, getColorMap, makeColorMap };
